<template>
    <div class="musicDetailCard" :class="[isMusicDetailCardShow ? '' : 'hide']">
        <div class="closeCard" @click="store.changeMusicDetailCardState()">
            <i class="iconfont icon-arrow-down"></i>
        </div>
        <div class="musicDetailContainer" >
            <div class="top">
                <div class="left">
                    <div class="discContainer">
                        <div class="needle" :class="store.isPlay ? 'needleRotate' : ''">
                            <img src="../../static/needle.png" alt="">
                        </div>
                        <div class="disc" :class="[store.isPlay ? '' : 'pause',
                        store.isMuscLoad ? '' : 'discAnimation'
                        ]">
                            <img src="../../static/dis.png" alt="">
                            <img class="musicAvatar"
                                :src="musicInfo.al.picUrl" alt="">
                        </div>
                    </div>
                </div>
                <div class="right">
                    <div class="title">
                        <div class="musicName">
                            {{musicInfo.name}}
                        </div>
                        <div class="album">{{musicInfo.al.name}}</div>
                        <div class="singer">{{musicInfo.ar[0].name}}</div>
                    </div>
                    <div class="lyric" ref="lyricContainer">
                        <ul class="lrcList" v-if="lyricData" ref="ul">
                            <li v-for="(item, index) in lyricData" :key="index" ref="li">{{item.words}}</li>
                        </ul>
                        <div v-else>歌词加载中</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, reactive,onMounted } from 'vue'
import useStore from '../../store/idnex'
import request from '../../api/index'
import mitt from '../../utils/eventBus.js'
const store = useStore()
const isMusicDetailCardShow = ref(false)
// 是否删除卡片渲染的内容
const cleanCard = ref(false)
const lyricData = ref([])
// 一开始页面渲染会依赖musicInfo数据，防止报错，先初始化空数据
const musicInfo = ref({
    al:{
        name:'',
        picUrl:''
    },
    ar:[{name:''}]
})
const comment = ref({})

// 歌词容器dom
const lyricContainer = ref(null)
// 歌词uldom
const ul = ref(null)
//容器高度
const LyricContainerHeight = ref(null)

onMounted(() => {
    // 由于直接获取会报错，所以在mounted周期内获取
    LyricContainerHeight.value = lyricContainer.value.clientHeight
    mitt.on('setoffSet', setoffSet)
})


watch(() => store.isMusicDetailCardShow, (newVal) => {
    isMusicDetailCardShow.value = newVal
    // 如果卡片没有展示就不发送请求和渲染里面的内容
    // clearTimeout(timer)
    cleanCard.value = false
    if (isMusicDetailCardShow && store.musicId != '') {
        getLyric(store.musicId)
    }
    // 当卡片关闭时，延迟三秒再删除里面渲染的内容
    else if (isMusicDetailCardShow == false) {
        timer = setTimeout(() => {
            cleanCard.value = true
        }, 3000)
    }
})

// store中的musicId发生变化
watch(() => store.musicId,(newVal) => {
    // 清空歌词
    lyricData.value = [{time:0,words:"正在加载歌词"}]
    // 更新当前歌曲信息
    musicInfo.value = store.musicList[store.currentIndex]
    //性能优化，只有在展示卡片的时候才发送请求
    if (isMusicDetailCardShow) {
        getLyric(newVal)
    }
})

// 解析歌词时间
const parseTime = (timeStr) => {
    let parts = timeStr.split(":")
    return +parts[0] * 60 + +parts[1]
}

//计算出高亮显示的歌词下标
const findIndex = () => {
    let currentTime = store.currentTime
    let lrcIndex = lyricData.value.findIndex(item => item.time > currentTime)
    // 对于最后一句歌词直至结束的时间，应该对应最后一句歌词的索引
    return lrcIndex == -1 ? lyricData.value.length - 1 : lrcIndex - 1
}

// 请求并处理歌词
const getLyric = async (id) => {
    let res = await request('/lyric', { id })
    let lyrics = res.data.lrc.lyric
    let lines = lyrics.split('\n')
    let result = []
    lines.forEach(item => {
        let parts = item.split(']')
        let timeStr = parts[0].substring(1)
        let obj = {
            words: parts[1],
            time: parseTime(timeStr)
        }
        if (obj.words != '') {
            result.push(obj)
        }
    })
    lyricData.value = result
}

// 控制歌词列表偏移位置
const setoffSet = () => {
    let index = findIndex()
    //本来动态获取dom高度，但是这样做影响应能，反正容器高度和li高度都是固定的，就直接计算了
    let offset = 40 * index + 80 - (380 / 2)
    // 为了保证快播放完毕的时候歌词处于中间，所以设置最大偏移值
    // let maxoffSet = ul.value.clientHeight - lyricContainer.value.clientHeight 
    // 一开始偏移值是负值，也就是说不需要偏移，直接令offset为0
    if(offset < 0) offset =0
    // if (offset > maxoffSet)  offset = maxoffSet
    ul.value.style.transform = `translateY(-${offset}px)`
    // 去掉之前歌词的active样式
    let li = document.querySelector('.active')
    // 需要考虑一开始没有li有active的情况
    if (li) {
        li.classList.remove('active')
    }
    // 令当前歌词高亮
    li = ul.value.children[index]
    if (li) {
        li.classList.add('active')
        
    }
}
</script>

<style lang="scss" scoped>
.hide {
    bottom: calc(-100vh + 60px) !important;
    // 这里用transform不会引起回流，但是resize会导致transform引起拖影，定位脱离文档流，性能也不会太差
}

.musicDetailCard {
    position: fixed;
    width: 100%;
    height: calc(100vh - 60px);
    bottom: 60px;
    z-index: 99;
    transition: bottom 0.5s ease;
    background-color: white;
    background-image: linear-gradient(to bottom, #e3e2e3, white);

    .closeCard {
        .iconfont {
            position: absolute;
            top: 15px;
            left: 35px;
            font-size: 30px;
            color: #666666;
            cursor: pointer;
        }
    }

    .top {
        display: flex;
        justify-content: center;

        .left {
            width: 220px;
            margin: 0 30px 0 -40px;

            .discContainer {
                margin-top: 60px;
                width: 220px;
                position: relative;

                .needle {
                    position: relative;
                    left: 50%;
                    width: 88px;
                    height: 72px;
                    z-index: 1000;
                    transition: all 1s;
                    transform-origin: 5.3px 5.3px;

                    img {
                        width: 100%;
                    }
                }

                .disc {
                    width: 220px;
                    height: 220px;
                    position: relative;
                    top: -12px;

                    img:nth-child(1) {
                        width: 100%;
                    }

                    .musicAvatar {
                        position: absolute;
                        top: 30px;
                        left: 30px;
                        width: 160px;
                        z-index: -1;
                        border-radius: 50%;
                    }
                }
            }
        }

        .right {
            width: 380px;

            .title {
                width: 100%;
                text-align: center;
                font-size: 15px;
                color: #919191;
                margin: 30px 0 15px;

                div {
                    margin: 8px 0;
                }

                .musicName {
                    font-size: 25px;
                    color: #161616;
                }

                .album {}
            }

            .lyric {
                width: 100%;
                height: 275px;
                overflow-y: scroll;
                text-align: center;

                li {
                    height: 20px;
                    list-style: none;
                    font-size: 14px;
                    margin: 20px 20px;
                    transition: all 0.5s;
                    line-height: 20px;
                }
            }
            //隐藏滚动条样式
            ::-webkit-scrollbar {
                width: 0px;
                height: 0px;
            }
        }
    }
}

//高亮显示的歌词
.active{
    font-weight: 600;
    font-size: 18px!important;
    color: black;
}

// 针偏移的动画
.needleRotate {
    transform-origin: 5.3px;
    transform: rotate(22deg);
}

// 碟子旋转动画
.discAnimation {
    // infinite动画无限循环
    animation: disc 25s liner infinite;
    // 动画延迟一秒
    animation-delay: 1s;
}

@keyframes disc {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.pause {
    animation-play-state: paused;
}
</style>